package com.scau402.system.controller;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.scau402.common.constant.JadeInventoryStatusConstants;
import com.scau402.common.utils.SecurityUtils;
import com.scau402.system.service.ISysTenantService;
import com.scau402.system1.domain.po.WmsInboundOrderDetailPO;
import com.scau402.system1.domain.po.WmsInboundOrderPO;
import com.scau402.system1.service.IWmsInboundOrderService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.scau402.common.annotation.Log;
import com.scau402.common.core.controller.BaseController;
import com.scau402.common.core.domain.AjaxResult;
import com.scau402.common.enums.BusinessType;
import com.scau402.system.domain.WmsJade;
import com.scau402.system.service.IWmsJadeService;
import com.scau402.common.utils.poi.ExcelUtil;
import com.scau402.common.core.page.TableDataInfo;

/**
 * 单个翡翠信息Controller
 *
 * @author ruoyi
 * @date 2023-06-26
 */
@RestController
@RequestMapping("/system/jade")
public class WmsJadeController extends BaseController
{
    @Autowired
    private IWmsJadeService wmsJadeService;

    @Autowired
    private ISysTenantService tenantService;

    @Autowired
    private IWmsInboundOrderService inboundOrderService;

    /**
     * 查询单个翡翠信息列表
     */
    @PreAuthorize("@ss.hasPermi('system:jade:list')")
    @GetMapping("/list")
    public TableDataInfo list(WmsJade wmsJade,@RequestParam(value = "type", required = false) Long type)
    {
        startPage();
        if (type != null && (type < 0 || type > 4)) {
            return tableDataInfoError("状态参数错误");
        }
        if (type != null) {
            wmsJade.setOrderType(type.toString());
        }
        List<WmsJade> list = wmsJadeService.selectWmsJadeList(wmsJade);
        System.out.println();
        List<Long> wmsJadeIdList = Optional.ofNullable(list).orElse(new ArrayList<>()).stream().map(WmsJade::getId).collect(Collectors.toList());
        Map<Long, String> inboundTypeJadeIdMap = inboundOrderService.getInboundTypeList(wmsJadeIdList, type);
        // 过滤掉list中那些在inboundTypeJadeIdMap中没有对应值的元素
        if (null !=  type)
            list.removeIf(jade -> !inboundTypeJadeIdMap.containsKey(jade.getId()));
        for(WmsJade jade: list) {
            jade.setInventoryStatus(JadeInventoryStatusConstants.INVENTORY_STATUS_MAP.get(jade.getStatus()));
            jade.setOrderType(inboundTypeJadeIdMap.get(jade.getId()));
        }
        return getDataTable(list);
    }

    /**
     * 导出单个翡翠信息列表
     */
    @PreAuthorize("@ss.hasPermi('system:jade:export')")
    @Log(title = "单个翡翠信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, WmsJade wmsJade)
    {
        List<WmsJade> list = wmsJadeService.selectWmsJadeList(wmsJade);
        ExcelUtil<WmsJade> util = new ExcelUtil<WmsJade>(WmsJade.class);
        util.exportExcel(response, list, "单个翡翠信息数据");
    }

    /**
     * 获取单个翡翠信息详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:jade:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {

        WmsJade jade = wmsJadeService.selectWmsJadeById(id);
        jade.setInventoryStatus(JadeInventoryStatusConstants.INVENTORY_STATUS_MAP.get(jade.getStatus()));
        return success(jade);
    }

//    /**
//     * 新增单个翡翠信息
//     */
//    @PreAuthorize("@ss.hasPermi('system:jade:add')")
//    @Log(title = "单个翡翠信息", businessType = BusinessType.INSERT)
//    @PostMapping
//    public AjaxResult add(@RequestBody WmsJade wmsJade)
//    {
//        wmsJade.setCreateBy(getUsername());
//        return toAjax(wmsJadeService.insertWmsJade(wmsJade));
//    }

    /**
     * 修改单个翡翠信息
     */
    @PreAuthorize("@ss.hasPermi('system:jade:edit')")
    @Log(title = "单个翡翠信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody WmsJade wmsJade)
    {
        return toAjax(wmsJadeService.updateWmsJade(wmsJade));
    }

    /**
     * 删除单个翡翠信息
     */
    @PreAuthorize("@ss.hasPermi('system:jade:remove')")
    @Log(title = "单个翡翠信息", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(wmsJadeService.deleteWmsJadeByIds(ids));
    }

    /**
     * 获取翡翠编码
     *
     * @return
     * @throws InterruptedException
     */
    @PreAuthorize("@ss.hasPermi('system:jade:add')")
    @GetMapping("/getJadeCode")
    public String getJadeCode() throws InterruptedException {
        return wmsJadeService.getNewCode(SecurityUtils.getLoginUser().getUser());
    }

    /**
     * 获取库存状态
     *
     * @return
     * @throws InterruptedException
     */
    @PreAuthorize("@ss.hasPermi('system:jade:add')")
    @GetMapping("/getInventoryStatus")
    public AjaxResult getInventoryStatus() throws InterruptedException {
        AjaxResult result = AjaxResult.success();
        result.put("statusList", JadeInventoryStatusConstants.INVENTORY_STATUS_MAP.toString());
        return result;
    }


    /**
     * 根据 ImageId 获取 Jade
     * @param params
     * @return
     */
    @PreAuthorize("@ss.hasPermi('system:jade:add')")
    @PostMapping("/getJadeByImageId")
    public AjaxResult getJadeByImageId(@RequestBody String params)
    {
        // 转换 source_ids 为 list 格式
        JSONObject paramsJson =  JSON.parseObject(params);
        JSONArray jsonArray = paramsJson.getJSONArray("imageIds");

        List<Long> imageIds = JSONArray.parseArray(jsonArray.toJSONString(), Long.class);
        List<WmsJade> jades = wmsJadeService.selectJadesByImageIds(imageIds);

        return success(jades);
    }



}
